//
//  IJKFFMoviePlayerController+Additions.swift
//  live
//
//  Created by melvyn on 2018/8/19.
//  Copyright © 2018 NEET. All rights reserved.
//

import Foundation
import RxSwift
import RxCocoa

extension IJKFFOptions {
    public static var `default`: IJKFFOptions = {
        
        let options = IJKFFOptions.byDefault()!
//        options.setFormatOptionValue("nobuffer", forKey: "fflags")
//        options.setFormatOptionIntValue(4096, forKey: "probsize")
//        options.setPlayerOptionIntValue(1, forKey: "videotoolbox")
//        options.setPlayerOptionIntValue(2000000, forKey: "analyzeduration")
        
        return options
    }()
}

extension IJKFFMoviePlayerController {
    convenience init(url: URLConvertible, options: IJKFFOptions) {
        self.init(contentURL: try! url.asURL(), with: options)
    }
}

extension Reactive where Base: IJKFFMoviePlayerController {
    
    var isPlayable: Observable<Bool> {
        return movieLoadState.map { $0 == .playable }
    }
    
    var isBuffering: Observable<Bool> {
        return movieLoadState.map { $0 == .stalled }
    }
    
    var prepare: Binder<Void> {
        return Binder(base) { obj, _ in
            obj.prepareToPlay()
        }
    }
    
    var movieLoadState: Observable<IJKMPMovieLoadState> {
        return NotificationCenter.default.rx.notification(.IJKMPMoviePlayerLoadStateDidChange, object: self.base)
        .map({
            
            let obj = $0.object as! IJKFFMoviePlayerController
            return obj.loadState
        })
    }
    
    var moviePlaybackState: Observable<IJKMPMoviePlaybackState> {
        return NotificationCenter.default.rx.notification(.IJKMPMoviePlayerPlaybackStateDidChange, object: self.base).map {
            let obj = $0.object as! IJKFFMoviePlayerController
            return obj.playbackState
        }

    }
}
